<?php

namespace Admin\Controller;

use Zend\Form\Annotation\AnnotationBuilder;
use Admin\Controller\IndexController;
use Admin\Model\DBO\CiculationPolicyDBO;
use Admin\Form\PolicyCiculationForm;
use Admin\Entity\Policy;

class ListPolicyTrafficController extends IndexController {

    public $userTable;
    public $form;

    public function getForm() {
        if (!$this->form) {
            $policy = new PolicyCiculationForm();
            $builder = new AnnotationBuilder();
            $this->form = $builder->createForm($policy);
        }

        return $this->form;
    }

    public function indexAction() {
        // kiem tra neu chua dang nhap thi quay ve lai trang dang nhap
        $this->checkRole1();
        // Lay thuc the dang nhap dua ra layout
        $this->layout()->identity = $this->getAuthService()->getIdentity();
        // Hiển thị các chính sách lưu thông
        $objectCiculationPolicy = new CiculationPolicyDBO($this->getServiceLocator());
        $paginator = $objectCiculationPolicy->fetchAll();
        $paginator->setCurrentPageNumber((int) $this->params()->fromQuery('page', 1));
        $paginator->setItemCountPerPage(7);
        $paginator->setPageRange(5);
        return array(
            'paginator' => $paginator,
        );
    }

    public function editCiculationPolicyAction() {
        $this->checkRole1();
        $policyID = $this->params()->fromRoute('id', 0);
        try {
            $objectCiculationPolicy = new CiculationPolicyDBO($this->getServiceLocator());
            $policy = new Policy();
            $data = $objectCiculationPolicy->getCiculationPolicy($policyID);
            $policy->exchangeArray($data);
        } catch (\Exception $ex) {
            return $this->redirect()->toRoute('album', array(
                        'action' => 'index'
            ));
        }
        $form = $this->getForm();
        $form->bind($policy);
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $objectCiculationPolicy->updatePolicy($form->getData());

                // Redirect to list of albums
                return $this->redirect()->toRoute('list-policy-traffic');
            } else {
                  foreach ($form->getMessages() as $value => $ms) {
                    $myMessage[$value] = $value;
                }
            }
        }
        return array(
            'policyID' => $policyID,
            'form' => $form,
        );
    }

}

